package com.itheima.web.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.domain.Question;
import com.itheima.domain.Result;
import com.itheima.QuestionService;
import com.itheima.utils.BeanUtil;
import com.itheima.web.filters.BeanFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * http://localhost:8080/heima_mm/store/question/findByPage?currentPage=1&Size=5
 * 可以接受来自store/question下面多有的方法
 */
@WebServlet("/store/question/*")
public class QuestionServlet extends BaseServlet {
private QuestionService questionService= BeanFactory.getBean("questionService",QuestionService.class);
    private Result findByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        获取请求参数
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");
//        判断非空
        int currentPage = 1,pageSize=5;//定义默认的页码和每页条数
        if (!StringUtils.isBlank(_currentPage)){
            currentPage = Integer.parseInt(_currentPage);
        }if (!StringUtils.isBlank(_pageSize)){
             pageSize = Integer.parseInt(_pageSize);
        }
//        调用service层方法获取分页结果

        PageInfo<Question> info = questionService.findByPage(currentPage, pageSize);
//        对客户做出响应
        return new Result(true, MessageConstant.QUERY_CATALOG_SUCCESS,info);

    }
    private Result save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
//        获取请求参数并封装成Question对象
        try {
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
//            调用service层方法添加数据
            questionService.save(question);
//        响应结果
            return new Result(true,MessageConstant.SAVE_COMPANY_SUCCESS);
        } catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.SAVE_COMPANY_FAIL);
        }

    }
    private Result findById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
//        获得请求参数
            String questionId = request.getParameter("id");
//            调用Service层方法
            Question question = questionService.findById(questionId);
//       对客户做出响应
            return new Result(true,MessageConstant.QUERY_COMPANY_SUCCESS,question);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SAVE_COMPANY_FAIL);
        }

    }
    private Result edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
//        获取请求参数
        try {
            Question question = BeanUtil.fillBeanFromJson(request, Question.class);
//       调用serice层方法，修改数据
            questionService.update(question);
//        响应结果
            return new Result(true,MessageConstant.QUERY_COMPANY_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_COMPANY_FAIL);
        }
    }
    private Result delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
//        获取请求参数，封装成对象
            String[] ids = BeanUtil.fillBeanFromJson(request, String[].class);
//        调用service层方法，删除数据
            questionService.delete(ids);
//        响应结果
            return new Result(true,MessageConstant.DELETE_COMPANY_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_COMPANY_FAIL);
        }

    }
    private Result findAll(HttpServletRequest request, HttpServletResponse response) throws IOException{
        try {
            List<Question> list = questionService.findAll();
            return new Result(true,MessageConstant.QUERY_COURSE_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_COURSE_FAIL);
        }

    }
    /**
     * 处理文件上传的请求
     * @param request
     * @param response
     */
    private Result upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1 创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2 创建ServletFileUpload文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //3 解析请求，得到上传条目
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            //4 因为每次只会上传一张图片，不需要遍历
            FileItem fileItem = fileItems.get(0);
            //获取文件保存的位置
            String path = getServletContext().getRealPath("/upload");
            //原始文件名
            String filename = fileItem.getName();
            //需求：生成唯一不重复的文件名
            //生成唯一文件名
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //获取后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            //组合新的文件名
            filename = uuid + suffix;
            //写到硬盘中
            fileItem.write(new File(path, filename));
            return new Result(true, MessageConstant.UPLOAD_QUESTIONIMG_SUCCESS, filename);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.UPLOAD_QUESTIONIMG_FAIL);
        }
    }
    /**
     * 处理导出题目请求
     * @param request
     * @param response
     */
    private Result toExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            //1 设置content-disposition响应头，告诉浏览器以附件(文件下载)的方式弹框
            response.setHeader("content-disposition","attachment;filename=question.xlsx");
            //2 调用service层方法，生成xlsx表格，进行输出
            questionService.toExport(response.getOutputStream());
            //响应结果
            return new Result(true,MessageConstant.QUESTION_EXPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUESTION_EXPORT_FAIL);
        }
    }
}